package com.vint.mi;

import java.util.Stack;

/**
 * 四则运算，没有括号，小数则向下取
 */
public class Mi16 {
    public static String solution(String line){
        String[] src = line.split(" ");
        int len = src.length;
        Stack<String> stack = new Stack<>();
        try {
            for (int i = 0; i < len; i++) {
                if (src[i].equals("+") || src[i].equals("-")) {
                    stack.add(src[i]);
                } else if (src[i].equals("*") || src[i].equals("/")) {
                    if (stack.isEmpty()) {
                        return "err";
                    } else {
                        if (src[i].equals("*")) {
                            if (i == len - 1) return "err";
                            int sum = Integer.parseInt(stack.pop()) * Integer.parseInt(src[++i]);
                            stack.add(String.valueOf(sum));
                        } else {
                            if (i == len - 1) return "err";
                            int sum = Integer.parseInt(stack.pop()) / Integer.parseInt(src[++i]);
                            stack.add(String.valueOf(sum));
                        }
                    }
                } else {
                    stack.add(src[i]);
                }
            }
            Stack<String>back = new Stack<>();
            while (!stack.isEmpty()){
            	back.add(stack.pop());
            }
            int sum = Integer.parseInt(back.pop());
            while (!back.isEmpty()){
                String op = back.pop();
                if(back.isEmpty())return "err";
                int t = Integer.parseInt(back.pop());
                if(op.equals("+")){
                    sum += t;
                }else{
                   if(!op.equals("-"))return "err";
                    sum -= t;
                }
            }
            return String.valueOf(sum);
        }catch (NumberFormatException e){
            return "err";
        }catch (Exception e){
            return "err";
        }
    }
    public static void main(String[] args) {
        //System.out.println(solution("3 + 5 + 7"));
        //System.out.println(solution("1 / 2"));
        //System.out.println(solution("1 / 0"));
        System.out.println(solution("12 + 34 * 56 - 78"));
    }
}
